import hashlib
import redis
import base64
import os
import asyncio
import logging.config
from log import config
from tornado import web


logging.config.dictConfig(config)
logger = logging.getLogger(__name__)

redis_conn = {'host': '127.0.0.1',
              'port': 6379,
              'db': 0}
redis_pool = redis.ConnectionPool(**redis_conn)

def md5(value):
    m = hashlib.md5()
    m.update(value.encode('utf-8'))
    _hash = m.hexdigest()
    return _hash

class BaseHandler(web.RequestHandler):
    def initialize(self):
        self.redis = redis.Redis(connection_pool=redis_pool)
        self.redis_key = "chapter2:"

class IndexHandler(web.RequestHandler):

    def get_current_user(self):
        return self.get_secure_cookie("username")

    def set_current_user(self, username):
        pass

    # 首页:
    def get(self):
        if self.current_user:
            self.write(f'{bytes.decode(self.current_user)},欢迎回来')
            self.write("<p><a href='/logout'>退出用户</a></p>")
            self.write("<p><a href='/put'>修改密码</a></p>")
        else:
            self.write("欢迎你,<a href='/login'>登录</a>")


class LoginHandler(BaseHandler):

    def get(self):
        msg = self.get_cookie("error_msg", "")
        if msg:
            msg = base64.b64decode(msg)
        self.render("login.html", msg=msg)

    def post(self):
        username = self.get_body_argument("username")
        password = self.get_body_argument("password")
        is_login = False

        user_key = self.redis_key + username
        user_by_db = self.redis.get(user_key)
        if user_by_db and md5(password) == user_by_db.decode("utf-8"):
            is_login = True

        if is_login:

            self.set_secure_cookie("username", username)
            self.redirect("/")
        else:

            msg = bytes("用户名与密码不匹配", "utf-8")
            self.set_cookie("error_msg", base64.b64encode(msg))
            self.redirect("/login")

class RegisterHandler(BaseHandler):

    def get(self):
        msg = self.get_cookie("error_msg", "")
        self.render("register.html", msg=msg)

    def post(self, *args, **kwargs):
        username = self.get_body_argument("username")
        password = self.get_body_argument("password")
        password_ = self.get_body_argument("password_")
        msg = ""
        user_key = self.redis_key + username

        if password != password_:
            msg = "两次输入密码不一致"
        elif self.redis.exists(user_key):
            msg = "用户名已存在"
        else:
            password = md5(password)
        if not msg:
            # self.redirect("/login")
            self.redis.set(user_key, password)
            self.write(f"注册成功,用户名是: {username}")
        else:
            self.write(msg)

class LogoutHandler(web.RequestHandler):
    def get(self, *args, **kwargs):
        self.get_secure_cookie('username')
        self.clear_cookie('username')
        self.redirect("/")

class PutHandler(BaseHandler):
    def get_current_user(self):
        return self.get_secure_cookie("username")

    def set_current_user(self, username):
        pass

    def get(self):
        msg = self.get_cookie("error_msg", "")
        self.render("put.html", msg=msg)

    def post(self, *args, **kwargs):
        new_password = self.get_body_argument('new_password')
        new_password_ = self.get_body_argument('new_password_')
        msg = ""

        user = self.current_user.decode('utf-8')
        key = self.redis_key + user

        if new_password != new_password_:
            msg = "两次密码不一致"
        else:
            new_password = md5(new_password)
            self.redis.set(key, new_password)
        if not msg:
            self.write("密码修改成功")
        else:
            self.write(msg)



urls = [(r'/', IndexHandler),
        (r'/login', LoginHandler),
        (r'/reg', RegisterHandler),
        (r'/put', PutHandler),
        (r'/logout',LogoutHandler),]
BASR_DIR = os.path.dirname(__file__)
app = web.Application(urls, template_path=os.path.join(BASR_DIR, 'templates'),
                              cookie_secret="61oETzKXQAGaYdghdhgfhfhfg")
app.listen(8002)

loop = asyncio.get_event_loop()
loop.run_forever()

